package com.darren.framework.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.darren.framework.Exception.ArchiveException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.darren.framework.entity.SystemParameter;
import com.darren.framework.service.SystemParameterService;
import com.darren.framework.utils.Constant;

import net.sf.ehcache.Element;

@Controller
public class SystemParameterAction extends BaseAction{
	
	@Autowired
	private SystemParameterService systemParameterService;	
	
	@ResponseBody
	@GetMapping("/system/parameter/{id}")
	public  JSONObject getSystemParameterById(@PathVariable(name="id",required=true) Long  id){
		JSONObject responseJson = new JSONObject();	
		Element element = ehCacheManager.getCache(Constant.CACHE_SYSTEM_PARAMS).get(id);
		responseJson.put("message", "未正常获取！");
		SystemParameter paramter = null;
		if(element != null){
			paramter = (SystemParameter) element.getObjectValue();
			responseJson.put("message", "缓存获取！");
			logger.info("缓存获取！");
		}else{
			paramter = systemParameterService.findById(id);
			responseJson.put("message", "数据库获取！");
			logger.info("数据库获取！");
		}
		responseJson.put("status", 0);
		responseJson.put("data", paramter);
		return responseJson;
	}
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping("/system/parameters/list")
	public  JSONObject getSystemParameters(HttpServletRequest request){
		JSONObject responseJson = new JSONObject();	
		Element element = ehCacheManager.getCache(Constant.CACHE_SYSTEM_PARAMS).get("AllParam");
		responseJson.put("message", "未正常获取！");
		List<SystemParameter> paramters = null;
		if(element != null){
			paramters = (List<SystemParameter>)element.getObjectValue();
			responseJson.put("message", "缓存获取！");
			logger.info("从缓存中获取到所有系统参数！");
		}else{
			paramters = systemParameterService.getAllSystemParameter();
			element = new Element("AllParam",paramters);
			ehCacheManager.getCache(Constant.CACHE_SYSTEM_PARAMS).put(element);
			responseJson.put("message", "数据库获取！");
			logger.info("从数据库获取到所有系统参数！");
		}
		responseJson.put("status", 0);
		responseJson.put("data", paramters);
		if(responseJson != null){
			throw new ArchiveException("测试");
		}
		return responseJson;
	}
	

	
}
